/*
 * UserNet  --  TCP/IP implementation in userspace
 * Copyright (C) 2010  Alex Diban
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <errno.h>
#include <error.h>
#include "unet/dev.h"
#include "unet/routes.h"
#include "unet/rpc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "unet/misc.h"

// FIXME: this is only here to make build happy
void
unet_ip_incoming_packet ()
{
}

static void
route_list (int id)
{
  struct unet_route * route;
  route= malloc (sizeof(struct unet_route));

  if (unet_rpc_route_get(id,route)==-1)
  error (1, errno, "unet_rpc_route_get");
  
  printf("%s      ",inet_ntoa(route->Destination));
  printf("%s    ",inet_ntoa(route->Genmask));
  printf("%s    ",inet_ntoa(route->Gateway));
  printf("unet%d\n",route->id_interface);	 
  
}


int main(int argc, char *argv[]){
  
  char *option = argv[1];
  
  if (argc==1){
    printf("Destination  Gateway    Genmask    Iface\n");	         
    int i;
    int j=unet_rpc_route_count();
    if (j==-1) error (1, errno, "unet_rpc_route_count");
    else{
      for (i = 0; i < j; i++)
	route_list(i); 
      return 0;
      }
    }
  
  else if ( (argc == 6) && (strcmp("add",option)== 0) )
  { 
    struct unet_route * route;
    route= malloc (sizeof(struct unet_route));
    
    inet_aton(argv[2], &route->Destination);
    inet_aton(argv[3], &route->Genmask);
    inet_aton(argv[4], &route->Gateway);
    route->id_interface=atoi(argv[5] + 4);    
    
    if (unet_rpc_route_add(route) == -1){
      error (1, errno, "unet_rpc_route_add");
    }
    return 0;
  }
  
  else if ( (argc == 4) && (strcmp("del",option) == 0) )
  {
    struct unet_route * route;
    route= malloc (sizeof(struct unet_route));
    
    inet_aton(argv[2], &route->Destination);
    inet_aton(argv[3], &route->Genmask);
    route->interface=NULL;
    int r=unet_rpc_route_del(route);
    free(route);
    
    if (r==0) printf("Route deleted\n");
    else if (r==-1) error (1, errno, "unet_rpc_route_del");
    return 0;
  } 
  
  printf("Usage: route add [host] [mask] [gateway] [interface]\n"
	 "       route del [host] [mask]\n"
	 "       route: for list of routes\n");  
	 
  return 0;
}
